package com.company.manage.system.service;

import com.company.manage.common.base.BaseService;
import com.company.manage.common.persistence.HibernateDao;
import com.company.manage.system.dao.UserRoleDao;
import com.company.manage.system.entity.Role;
import com.company.manage.system.entity.User;
import com.company.manage.system.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by HuangYong on 2016/1/23.
 * desc:
 */
@Service
@Transactional(readOnly = false)
public class UserRoleService extends BaseService<UserRole, Integer> {
    private static final String TAG = "UserRoleService";

    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    public HibernateDao<UserRole, Integer> getEntityDao() {
        return userRoleDao;
    }

    /**
     * 添加修改用户角色
     *
     * @param userId
     * @param oldList
     * @param newList
     */
    public void updateUserRole(Integer userId, List<Integer> oldList, List<Integer> newList) {
        /*1.删除旧的用户角色关系*/
        for (int i = 0; i < oldList.size(); i++) {
            if (!newList.contains(oldList.get(i))) {
                userRoleDao.deleteUserRole(userId, oldList.get(i));
            }
        }
        /*2.添加新的用户角色关系*/
        for (int i = 0; i < newList.size(); i++) {
            if (!oldList.contains(newList.get(i))) {
                userRoleDao.save(getUserRole(userId, newList.get(i)));
            }
        }
    }

    /**
     * 封装新的UserRole对象
     *
     * @param userId
     * @param roleId
     * @return UserRole
     */
    private UserRole getUserRole(Integer userId, Integer roleId) {
        UserRole userRole = new UserRole();
        userRole.setUser(new User(userId));
        userRole.setRole(new Role(roleId));
        return userRole;
    }

    /**
     * 根据用户id查询具有的角色id
     * @param userId
     * @return
     */
    public List<Integer> getRoleIdList(Integer userId){
        return userRoleDao.findRoleId(userId);
    }

}